# coding=utf-8
import time

INTERVALS = 10


def get_str_red(str_data):
    return "\033[31m{}\033[0m".format(str_data)


def get_hit_from_proc_vmstat():
    # -- 1 ---
    # 读取/proc/vmstat文件
    with open('/proc/vmstat', 'r') as f:
        lines = f.readlines()

    # 初始化命中和未命中的次数
    pgpgin_count = 0
    pgpgout_count = 0

    # 解析文件中的pgpgin和pgpgout值
    for line in lines:
        if line.startswith('pgpgin'):
            pgpgin_count += int(line.split()[1])
        elif line.startswith('pgpgout'):
            pgpgout_count += int(line.split()[1])

    # print(pgpgin_count, pgpgout_count)
    print("wait {}s...".format(INTERVALS))
    time.sleep(INTERVALS)

    # -- 2 ---
    with open('/proc/vmstat', 'r') as f1:
        lines = f1.readlines()

    # 初始化命中和未命中的次数
    pgpgin_count_new = 0
    pgpgout_count_new = 0

    # 解析文件中的pgpgin和pgpgout值
    for line in lines:
        if line.startswith('pgpgin'):
            pgpgin_count_new += int(line.split()[1])
        elif line.startswith('pgpgout'):
            pgpgout_count_new += int(line.split()[1])

    # print(pgpgin_count_new, pgpgout_count_new)
    pgpgin_count = pgpgin_count_new - pgpgin_count
    pgpgout_count = pgpgout_count_new - pgpgout_count
    print("vm缓存命中次数: {}".format(pgpgin_count))
    print("vm缓存未命中次数: {}".format(pgpgout_count))
    print("vm缓存命中率: {} %".format(get_str_red(pgpgin_count/(pgpgout_count + pgpgin_count) * 100)))
    print("\n")


def get_hit_from_proc_stat():
    # -- 1 ---
    # 读取/proc/stat文件
    with open('/proc/stat', 'r') as f:
        lines = f.readlines()

    # 解析文件中的 Time spent in system mode, Time spent in the idle task
    cpu_system = 0
    cpu_idle = 0
    for line in lines:
        if line.startswith("cpu "):
            cpu_info = line.split()
            # print(cpu_info)
            if len(cpu_info) > 4:
                cpu_system += int(cpu_info[3])
                cpu_idle += int(cpu_info[4])
    # print(cpu_system, cpu_idle)
    print("wait {}s...".format(INTERVALS))
    time.sleep(INTERVALS)
    # -- 2 ---
    with open('/proc/stat', 'r') as f1:
        lines = f1.readlines()

    # 解析文件中的 Time spent in system mode, Time spent in the idle task
    cpu_system_new = 0
    cpu_idle_new = 0
    for line in lines:
        if line.startswith("cpu "):
            cpu_info = line.split()
            if len(cpu_info) > 4:
                cpu_system_new += int(cpu_info[3])
                cpu_idle_new += int(cpu_info[4])

    # print(cpu_system_new, cpu_idle_new)
    cpu_system = cpu_system_new - cpu_system
    cpu_idle = cpu_idle_new - cpu_idle
    print("cpu缓存命中次数: {}".format(cpu_system))
    print("cpu缓存未命中次数: {}".format(cpu_idle))
    print("cpu缓存命中率: {} %".format(get_str_red(cpu_system/(cpu_system + cpu_idle) * 100)))
    print("\n")


if __name__ == '__main__':
    get_hit_from_proc_stat()
    get_hit_from_proc_vmstat()
